<template>
  <a-card>
    <div>
      <a-form layout="horizontal">
        <div class="fold">
          <a-row>
            <a-col :md="6" :sm="24">
              <a-form-item label="时间" :labelCol="{ span: 5, offset: 1 }" :wrapperCol="{ span: 17, offset: 1 }">
                <a-date-picker format="YYYY-MM-DD" v-model="date" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="搜索" :labelCol="{ span: 5, offset: 1 }" :wrapperCol="{ span: 17, offset: 1 }">
                <a-input v-model="search" placeholder="请输入" allowClear />
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <span style="float: right; margin-top: 3px">
          <a-button type="primary" @click="query">查询</a-button>
          <a-button @click="exportExcel" style="margin-left: 10px" :loading="logging">导出</a-button>
        </span>
      </a-form>
    </div>
    <div>
      <a-table :columns="columns" :dataSource="dataSource" :pagination="pagination"
        :rowKey="(dataSource) => dataSource.Id">
        <template slot="time" slot-scope="text">
          {{ text | dateTimeFormat }}
        </template>
        <template slot="ellipsis" slot-scope="text">
          <a-tooltip placement="bottom" :title="text">
            {{ text.length > 80 ? text.substring(0, 80) + '...' : text }}
          </a-tooltip>
        </template>
      </a-table>
    </div>
  </a-card>
</template>

<script>
import { logService } from '/src/services'
import moment from 'moment'
import ExportJsonExcel from "js-export-excel"

const columns = [
  {
    title: '序号',
    width: 60,
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    title: '创建日期',
    width: 160,
    dataIndex: 'CreateTime',
    scopedSlots: { customRender: 'time' }
  },
  {
    title: 'Sql',
    dataIndex: 'Sql',
    width: 530,
    scopedSlots: { customRender: 'ellipsis' }
  },
  {
    title: '参数',
    dataIndex: 'Param',
    width: 530,
    scopedSlots: { customRender: 'ellipsis' }
  }
]

export default {
  name: 'DataLogReport',
  filters: {
    dateTimeFormat(val) {
      if (val == null) return ''
      return val.replace('T', ' ').substring(0, 19)
    }
  },
  data() {
    return {
      advanced: false,
      columns: columns,
      dataSource: [],
      model: {},
      search: '',
      date: moment(),
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
        showTotal: (total) => `总计 ${total} 条`,
        onChange: (current, pageSize) => {
          this.pagination.pageSize = pageSize
          this.pagination.current = current
          this.loadData()
        }
      },
      pageIndex: 1,
      pageSize: 15,
      logging: false,
    }
  },
  mounted: function () {
    this.loadData()
  },
  methods: {
    async loadData() {
      var date = '';
      if (this.date) {
        date = this.date.format('YYYY-MM-DD');
      }
      var result = await logService.getDataBaseLogs(date, this.search, this.pagination.pageSize, this.pagination.current)
      if (result && result.data) {
        this.dataSource = result.data.data
        this.pagination.total = result.data.total
      }
    },
    query() {
      this.pagination.current = 1
      this.loadData()
    },
    async exportExcel() {
      this.logging = true;
      var date = '';
      if (this.date) {
        date = this.date.format('YYYY-MM-DD');
      }
      var result = await logService.getDataBaseLogs(date, this.search, 10000, 1)

      if (result && result.data) {
        var option = {};
        let dataTable = [];
        let datas = result.data.data;

        datas.forEach(item => {
          item.CreateTime = item.CreateTime.replace('T', ' ').substring(0, 19)
          dataTable.push(item);
        });
        var sheetFilter = [];
        var sheetHeader = [];
        columns.forEach(item => {
          if (item.title !== "序号" && item.title !== "操作") {
            sheetFilter.push(item.dataIndex)
            sheetHeader.push(item.title)
          }
        })
        option.fileName = this.$route.name + '_' + moment().format('YYYY-MM-DD');
        option.datas = [
          {
            sheetData: dataTable,
            sheetName: 'sheet',
            sheetFilter: sheetFilter,
            sheetHeader: sheetHeader,
          }
        ];
        var toExcel = new ExportJsonExcel(option);
        toExcel.saveExcel();
        this.logging = false;
      }

    },
    jsonFormat(format) {
      let msg = '', pos = 0, prevChar = '', outOfQuotes = true;
      for (let i = 0; i < format.length; i++) { //循环每一个字符
        let char = format.substring(i, i + 1);  //获取到该字符
        if (char == '"' && prevChar != '\\') {  //如果转移
          outOfQuotes = !outOfQuotes;
        } else if ((char == '}' || char == ']') && outOfQuotes) {   //如果是关闭
          msg += "<br/>";
          pos--;
          for (let j = 0; j < pos; j++) msg += '    ';
        }
        msg += char;
        if ((char == ',' || char == '{' || char == '[') && outOfQuotes) {
          msg += "<br/>";
          if (char == '{' || char == '[') pos++;
          for (let k = 0; k < pos; k++) msg += '    ';
        }
        prevChar = char;
      }
      return msg;
    }
  }
}
</script>

<style lang="less">
.search {
  margin-bottom: 54px;
}

.fold {
  width: calc(100% - 216px);
  display: inline-block;
}

.operator {
  margin-bottom: 18px;
}

@media screen and (max-width: 900px) {
  .fold {
    width: 100%;
  }
}

.ant-table-tbody .ant-table-row-cell-break-word {
  word-break: break-all;
}
</style>

